/* model */
import MsgModel from '@model/MsgModel';
/* utils */
import { 
  DingtalkOpenAuthTypeEnum, 
  isArray, 
  isEmpty, 
  isFalsy, 
  openDingtalkAuth as openDingtalkAuthBase 
} from 'pub-bbx-utils';
import { getRootWindow } from '@src/util/platform';
import { message } from '@src/util/message';
/* model */
import { DingtalkAuthTypeItem } from "@model/dingtalk";
/* api */
import { addDingScope, checkDingScope, refreshDingToken } from '@src/api/AuthApi';

async function openDingtalkAuth(authItems: DingtalkAuthTypeItem[] | DingtalkAuthTypeItem) {
  
  console.log('dd.auth openDingtalkAuth authItems: ', authItems)
  
  if (isFalsy(isArray(authItems))) {
    authItems = [authItems] as DingtalkAuthTypeItem[]
  }
  
  // 校验的权限项
  const _authItems = authItems as DingtalkAuthTypeItem[]
  
  // 去后端校验权限是否已授权
  const checkDingScopeResult = await checkDingScope(_authItems)
  
  console.log('dd.auth openDingtalkAuth checkDingScopeResult: ', checkDingScopeResult)
  
  // 校验失败
  if (MsgModel.isFail(checkDingScopeResult)) {
    message.error(checkDingScopeResult.message)
    return
  }
  
  const needDingtalkAuthScopeData = MsgModel.getData(checkDingScopeResult, { scopeList: [] as DingtalkAuthTypeItem[] })
  if (isEmpty(needDingtalkAuthScopeData)) {
    console.log('授权校验失败, 数据为空')
    return
  }
  
  const needDingtalkAuthScopeList = needDingtalkAuthScopeData?.scopeList || [] as DingtalkAuthTypeItem[]
  if (isEmpty(needDingtalkAuthScopeList)) {
    console.log('没有需要授权的钉钉权限')
    return
  }
  
  console.log('dd.auth openDingtalkAuth needDingtalkAuthScopeList: ', needDingtalkAuthScopeList)
  
  const dingtalkAuthScopeList = needDingtalkAuthScopeList.map(item => {
    return {
      ...item,
      type: item.type || DingtalkOpenAuthTypeEnum.Personal
    }
  })
  
  for (let i = 0; i < dingtalkAuthScopeList.length; i++) {
    const authItem = dingtalkAuthScopeList[i]
    await openDingtalkAuthItem(authItem)
  }
  
}

async function openDingtalkAuthItem(authItem: DingtalkAuthTypeItem) {
  try {
    
    console.log('dd.auth openDingtalkAuthItem authItem: ', authItem)
    
    const rootWindow = getRootWindow(window)
    const response = await rootWindow.openDingtalkAuth(authItem)
    const authCode = response.result?.authCode || ''
    const newAuthItem = {
      rpcScope: authItem.rpcScope,
      fieldScope: authItem.fieldScope,
    }
    
    const params = {
      authCode: authCode,
      scopeList: [newAuthItem]
    }
    
    console.log('openDingtalkAuthItem params: ', params)
    
    const addDingScopeResult = await addDingScope(params)
    
    console.log('openDingtalkAuthItem addDingScopeResult: ', addDingScopeResult)
    
    if (MsgModel.isFail(addDingScopeResult)) {
      message.error(addDingScopeResult.message)
      return
    }
    
  } catch (error) {
    console.error('openDingtalkAuthItem error', error)
  }
}

export {
  openDingtalkAuth
}
